package com.mobileClientKernel.android.commonLayer;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Reader;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.security.MessageDigest;
import java.util.Enumeration;
import java.util.UUID;

public class UniqueIDUtil {

    //保存设备id到sp中tag
    private static final String DSSPTAG = "TEMP_DEVICE_ID";
    //获取设备id时的特殊值
    private static final String deviceid_Unknown = "Unknown";
    private static final String deviceid_0 = "0";
    private static final String deviceid_1111111111 = "1111111111";
    private static final String deviceid_0000000000 = "0000000000";
    private static String deviceId = null;

    /**
     * 获取设备id,获取不到则使用mac字符串
     *
     * @param context
     * @return
     */
    public static String getDeviceId(Context context) {
        deviceId = "";
        try {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

            if (TextUtils.isEmpty(deviceId)) {
                // 获取设备编号
                String tmpId = tm.getDeviceId();
                // 对设备编号的特殊值处理
                if (!TextUtils.isEmpty(tmpId)) {
                    if (tmpId.indexOf(deviceid_1111111111) >= 0
                            || tmpId.indexOf(deviceid_0000000000) >= 0
                            || tmpId.equals(deviceid_0)
                            || tmpId.equals(deviceid_Unknown)
                            || tmpId.length() < deviceid_Unknown.length())
                        deviceId = getMacIp(context).replace(":", "");//使用wifi mac地址
                    else
                        deviceId = tmpId;
                } else {    //使用wifi mac地址
                    deviceId = getMacIp(context).replace(":", "");
                }
            }
        } catch (Exception e) {

        }

        return deviceId;

    }



    /**
     * 生成一个UUID
     *
     * @return
     */
    public static String getUUID() {
        return UUID.randomUUID().toString();
    }

    /**
     * 获取设备名称
     *
     * @return
     */
    public static String getDeviceName() {
        try {
            return new Build().MANUFACTURER;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 获取系统版本
     *
     * @return
     */
    public static String getOSVersion() {
        try {
            return Build.VERSION.RELEASE;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 获取设备型号
     *
     * @return
     */
    public static String getDeviceModel() {
        try {
            return Build.MODEL;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 获取手机mac地址
     *
     * @param mContext
     * @return
     */
    public static String getMacIp(Context mContext) {
        String str = "";
        String macSerial = "";
        try {
            Process pp = Runtime.getRuntime().exec(
                    "cat /sys/class/net/wlan0/address ");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);

            for (; null != str; ) {
                str = input.readLine();
                if (str != null) {
                    macSerial = str.trim();// 去空格
                    break;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (macSerial == null || "".equals(macSerial)) {
         /*   try {
                return loadFileAsString("/sys/class/net/eth0/address")
                        .toUpperCase().substring(0, 17);
            } catch (Exception e) {
                e.printStackTrace();
                return "";
            }*/

            try {
                WifiManager wifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
                WifiInfo info = wifi.getConnectionInfo();
                return info.getMacAddress();
            } catch (Exception e) {
                e.printStackTrace();
                return "";
            }
        } else {
            return macSerial;
        }

    }

    private static String loadFileAsString(String fileName) throws Exception {
        FileReader reader = new FileReader(fileName);
        String text = loadReaderAsString(reader);
        reader.close();
        return text;
    }

    private static String loadReaderAsString(Reader reader) throws Exception {
        StringBuilder builder = new StringBuilder();
        char[] buffer = new char[4096];
        int readLength = reader.read(buffer);
        while (readLength >= 0) {
            builder.append(buffer, 0, readLength);
            readLength = reader.read(buffer);
        }
        return builder.toString();
    }

    /**
     * 获取当前ip地址
     *
     * @param context
     * @return
     */
    public static String getLocalIpAddress(Context context) {
//        try {
//            WifiManager wifiManager = (WifiManager) context
//                    .getSystemService(Context.WIFI_SERVICE);
//            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
//            int i = wifiInfo.getIpAddress();
//            return int2ip(i);
//        } catch (Exception ex) {
//            return "";
//        }
        // return null;
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        // if (!inetAddress.isLoopbackAddress() && inetAddress
                        // instanceof Inet6Address) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (Exception e) {
        }
        return "";
    }

    /**
     * 将ip的整数形式转换成ip形式
     *
     * @param ipInt
     * @return
     */
    public static String int2ip(int ipInt) {
        try {
            StringBuilder sb = new StringBuilder();
            sb.append(ipInt & 0xFF).append(".");
            sb.append((ipInt >> 8) & 0xFF).append(".");
            sb.append((ipInt >> 16) & 0xFF).append(".");
            sb.append((ipInt >> 24) & 0xFF);
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 获取版本号
     *
     * @return
     */
    public static int getVersionCode(Context context) {
        int versionCode = 0;
        try {
            versionCode = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException ex) {
            versionCode = 0;
        }
        return versionCode;
    }

    /**
     * 获取当前系统版本名
     *
     * @return
     */
    public static String getVersionName(Context context) {
        String name = "";
        try {
            name = context
                    .getPackageManager()
                    .getPackageInfo(context.getPackageName(),
                            0).versionName;
        } catch (PackageManager.NameNotFoundException ex) {
            name = "";
        }
        return name;
    }

    /**
     * 获取当前apk 的MD5
     */
    public static String getApkMd5(Context context) {
        PackageInfo pi = null;
        StringBuffer sb = new StringBuffer();
        try {
            pi = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
            Signature signatures = pi.signatures[0];
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(signatures.toByteArray());
            byte[] digest = md.digest();
            String res = toHexString(digest);
            sb.append(res);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    public static String toHexString(byte[] block) {

        StringBuffer buf = new StringBuffer();
        int len = block.length;
        for (int i = 0; i < len; i++) {
            byte2hex(block[i], buf);
            if (i < len - 1) {
                buf.append(":");
            }
        }
        return buf.toString();
    }

    private static void byte2hex(byte b, StringBuffer buf) {

        char[] hexChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
                '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        int high = ((b & 0xf0) >> 4);
        int low = (b & 0x0f);
        buf.append(hexChars[high]);
        buf.append(hexChars[low]);
    }

}
